package com.how2java.springboot.controller;

import com.how2java.springboot.mapper.CategoryMapper;
import com.how2java.springboot.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;


@Controller
public class CategoryController {
    @Autowired
     CategoryMapper categoryMapper;

    @RequestMapping("/listCategory")
    public String listCategory(Model m)throws Exception{
        List<Category> cs = categoryMapper.findall();
        m.addAttribute("cs",cs);
        return "listCategory";
    }
    @PutMapping("/category")
    public String listCategory(Category c) throws Exception{
        System.out.println("进入添加");
        categoryMapper.save(c);
        return "redirect:listCategory";
    }
    @DeleteMapping("/category/{id}")
    public void deleteCategory(@PathVariable("id") int id, HttpServletResponse response) throws Exception{
        System.out.println("删除 ："+id);
        categoryMapper.delete(id);
        String msg = "suc";
        response.getWriter().print("suc");//直接向前台发送msg
    }
    @PostMapping("/updateCategory")
    public String updateCategory(Category c) throws Exception{
        categoryMapper.update(c);
        return "redirect:listCategory";
    }
    @RequestMapping("/category/{id}")
    public String listCategory(@PathVariable("id") int id,Model m) throws  Exception{
        Category c = categoryMapper.get(id);
        m.addAttribute("c",c);
        return "editCategory";
    }
    @RequestMapping("/uploadPage")
    public String uploadPage(){
        return "uploadPage";
    }
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(HttpServletRequest req, @RequestParam("file")MultipartFile file,Model m){
        try {
            String fileName = System.currentTimeMillis()+file.getOriginalFilename();
            String destFileName=req.getServletContext().getRealPath("")+"uploaded"+ File.separator+fileName;

            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            file.transferTo(destFile);

            m.addAttribute("fileName",fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }

        return "showImg";
    }
}
